import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import to from 'await-to-js'
import type { PayloadAction } from '@reduxjs/toolkit'
import { login, info } from '@/api/login'
import type { TypeLoginParams, TypeInfos } from '@/api/login/type'

export interface UsersState {
    token: string
    infos: TypeInfos
}

const userStore = createSlice({
    name: 'userStore',
    initialState: {
        token: '',
        infos: {}
    } as UsersState,
    reducers: {
        //  更新 Token
        updateToken(state, action: PayloadAction<UsersState['token']>) {
            state.token = action.payload
        },
        // 更新 用户信息
        updateInfos(state, action: PayloadAction<UsersState['infos']>) {
            state.infos = action.payload
        },
        //  清除 Token
        clearToken(state) {
            state.token = '';
        }
    }
})
export const loginAction = createAsyncThunk(
    'userStore/loginAction',
    async (payload: TypeLoginParams, dispatch) => {
        const [ error, res ] = await to(login(payload))
        error && console.error(error)
        return res
    })

export const infoAction = createAsyncThunk(
    'userStore/infoAction',
    async () => {
        const [ error, res ] = await to(info())
        error && console.error(error)
        return res
    }
)
export const { updateToken, updateInfos, clearToken } = userStore.actions

export default userStore.reducer;
